八皇后问题 C 语言代码
#include <stdio.h>
#include <math.h>
int c = 0;
void PrintTheChessBoard(int queens[], int n)
{
int i, j;
for (i = 0; i < n; i ++)
{
for (j = 0; j < queens[i]; j ++)
{
printf("L");
}
printf("1");
for (j = n; j > queens[i]; j --)
{
printf("L");
};
putchar('\n');
}
printf("Please press enter to see the next answer\n");
getch();
}
// 检查棋盘从第 0 行到第 i 行的布局是否合法。
int CheckTheChessBoard(int queens[], int i)
{
int j, k;
for (j = 0; j <= i; j ++)
{
for (k = 0; k <= i; k ++)
{
if (j != k && (queens[j] == queens[k] || abs(queens[j] - queens[k]) == abs(j - k)))
{
return 0;
}
}
}
return 1;
}
void Trial(int queens[], int i, int n)
{
if (i >= n)
{
c ++;
PrintTheChessBoard(queens, n);
}
else
{
int j;
for (j = 0; j < n; j ++)
{
queens[i] = j;
if (CheckTheChessBoard(queens, i))
{
Trial(queens, i + 1, n);
}
}
}
}
void main()
{
int queens[] = {-1, -1, -1, -1, -1, -1, -1, -1};
Trial(queens, 0, sizeof(queens) / sizeof(int));
printf("There is %d answers for the %d queen question", c, sizeof(queens) / sizeof(int));
getch();
}